package org.proddevplm.servlets;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.proddevplm.business.ManagerFactory;
import org.proddevplm.constants.ControllerConstants;
import org.proddevplm.constants.UserConstants;
import org.proddevplm.dao.data.User;
import org.proddevplm.dao.util.HibernateUtil;

public class ControllerServlet extends HttpServlet {

    private ManagerFactory managerFactory = new ManagerFactory();
    private Map<String, Object> stateMap = new HashMap<String, Object>();

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp)
            throws ServletException, IOException {
        doPost(req, resp);
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp)
            throws ServletException, IOException {

        System.out.println("post");
        try {
        	
        	String manager = req.getParameter(ControllerConstants.MANAGER_KEY);
	        Integer method = Integer.valueOf(req.getParameter(ControllerConstants.METHOD_KEY));
	
	        System.out.println(manager + " " + method);
	        /*
	        if( (req.getSession().getAttribute(UserConstants.USER) == null)&&(!((manager.equals("userManager"))&&(method==5)))){
	        	resp.sendRedirect("/proddev/pages/startPage.jsp");
	        }else{
	        */
		    Object adaptedObject = managerFactory.adapt(manager, method, req.getParameterMap());
		    System.out.println(adaptedObject);
		    stateMap.clear();
		    HibernateUtil.currentSession().beginTransaction();
		
		    Object returnedObject = managerFactory.execute(manager, method, adaptedObject, stateMap, req.getSession());
		
		    HibernateUtil.currentSession().getTransaction().commit();
		    HibernateUtil.closeSession();
		    System.out.println(adaptedObject + " " + returnedObject);
		    req.getSession().setAttribute(ControllerConstants.STATE_MAP, stateMap);
		           
		    if (req.getParameter(ControllerConstants.AJAX) == null) {
		        resp.sendRedirect("/proddev/pages/index.jsp");
		    } else {
		        //XML String
		      	if(returnedObject!=null){
		           	resp.getOutputStream().println(returnedObject.toString());
		        }
		    }
	      //  }
        } catch (Exception e) {
            e.printStackTrace();
        	req.getSession().invalidate();
            resp.sendRedirect("/proddev/pages/index.jsp");
        }
    }

}